﻿using UnityEngine;
using System.Collections;

namespace net {
	public class LevelUp : MonoBehaviour {
		NetLvConfig netLvCfg ;
		bool isP1player=true;
		GameObject myTank =null;

		void Start(){
			netLvCfg = transform.root.gameObject.GetComponent<NetLvConfig>();
		}


		void OnMouseDown() {
			//寻找tank
			if(myTank == null){
				NetCtrl[] tanks = GameObject.FindObjectsOfType<NetCtrl>();
					foreach(NetCtrl obj in tanks){
						if(obj.networkView.isMine){
							myTank = obj.gameObject;
							break;
						}	
					}
			}
			if (NetMain.assetCount >= 100) {
				print ("levelup");
				// 升级，换图

				//判断是哪个玩家的坦克升级
				if(myTank.tag.Equals("TANK_PLAYER_P2")){
					isP1player = false;
				}

				NetPlayerState state = myTank.GetComponent<NetPlayerState>();

				//如果坦克已经是最高级，就不升级了
				if(state.level >= 4){
					return;
				}
				//找到坦克获得数据包
				NetLvPkg pkg = netLvCfg.findByLv(state.level+1);
				//价钱不够不能买
				if(NetMain.assetCount<pkg.buyPrice){
					return ;
				}
			

				//给坦克升级
				state.speed = pkg.speed;
				state.armor = pkg.armor;
				state.buyprice = pkg.buyPrice;
				state.sellprice = pkg.sellPrice;
				//换图... 因为数组以0开始算起，所以直接传level就是下一级的图片
				if(isP1player){
					myTank.GetComponent<SpriteRenderer>().sprite = netLvCfg.p1LvPicture[state.level];
				}
				else{
					myTank.GetComponent<SpriteRenderer>().sprite = netLvCfg.p2LvPicture[state.level];
				}
				//更新坦克等级信息
				state.level++;

print("is P1 tank"+isP1player+
	 "\n tank.armor = "+state.armor+
	"\n tank.level="+state.level);

				networkView.RPC("callLvUp",
				                RPCMode.All,
				                state.armor,
				                state.sellprice,
				                state.level,
				                isP1player,
				                myTank.networkView.viewID);
				// 扣物资
				NetMain.assetCount -= pkg.buyPrice;
			}
		}

		[RPC]
		public void callLvUp(int armor,int sellprice,int level,bool isP1,NetworkViewID id){
			GameObject tank = NetworkView.Find(id).gameObject;
			if(!tank.networkView.isMine){
print("接收到升级同步信息\n");
print("is P1 tank"+isP1player+
   	 "\n tank.armor = "+armor+
	 "\n tank.level="+level);

				tank.GetComponent<NetPlayerState>().armor = armor;
				tank.GetComponent<NetPlayerState>().sellprice = sellprice;
				tank.GetComponent<NetPlayerState>().level = level;
				if(isP1){
					tank.GetComponent<SpriteRenderer>().sprite = netLvCfg.p1LvPicture[level-1];
				}
				else{
					tank.GetComponent<SpriteRenderer>().sprite = netLvCfg.p2LvPicture[level-1];
				}

			}
		}

	}
}